from PyQt5.QtWidgets import QWidget,QHBoxLayout,QVBoxLayout,QPushButton, QLabel, QApplication, QLineEdit
from PyQt5.QtCore import Qt,QThread,pyqtSignal
from PyQt5.QtGui import QIcon, QPixmap, QPalette, QBrush
import os, time, sys
import socket,time
from uiDef import *

class TCPServer(QThread):
    signal_data = pyqtSignal(str,str)
    signal_exit = pyqtSignal()
    
    def __init__(self):
        super().__init__()
        self.exit = False

    def __del__(self):
        self.wait()

    def run(self):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            host = socket.gethostbyname(socket.gethostname())
            port = 6666
            if sys.platform.startswith('linux'):
                host = '192.168.5.110'
            else:
                host = '192.168.5.100'
            print(host)
            print(port)
            s.bind((host,port))
            s.listen(5)
            print('等待客户端连接中…')
            client,client_address = s.accept()
            print('新连接')
            client_IP = str(client_address[0])
            print('IP:'+client_IP)
            client_port = str(client_address[1])
            print('Port:' + client_port)
            try:
                while self.exit == False:
                    data = client.recv(30)
                    if data:
                        print('接收到消息 {}({} bytes) 来自 {}'.format(data.decode('utf-8'), len(data), client_address))
                        split_data = str(data).split(" ")
                        print(split_data)
                        temp = split_data[1]
                        humi = split_data[2]
                        print('temp:{} humi:{} '.format(temp,humi))
                        self.signal_data.emit(temp,humi)
                    else:
                        print('客户端 {} 已断开！'.format(client_address))
                        break
            finally:
                print("close TCPServer")
                client.close()
        except Exception as e:
            print(e)

    def stop(self):
        print("prepare stop TCPServer")
        self.exit = True
                
class DHT11Widget(QWidget):
    def __init__(self):
        super().__init__()

        #返回主界面
        self.homeBtn = QPushButton(self)
        self.homeBtn.setStyleSheet("QPushButton{border-image: url(resource/ic_home.png)}")
        self.homeBtn.setFixedSize(30, 30)
        self.headerLabel = QLabel(self)
        self.headerLabel.setText("车内温湿度")
        self.headerLabel.setStyleSheet("color:white")
        self.hBoxHeader = QHBoxLayout()
        self.hBoxHeader.addStretch(1)
        self.hBoxHeader.addWidget(self.headerLabel)
        self.hBoxHeader.addStretch(1)
        self.hBoxHeader.addWidget(self.homeBtn)
        
        self.tempLabel = QLabel(self)
        self.tempLabel.setText("温度:")
        self.tempLabel.setStyleSheet("font-size:50px; color:white")
        self.tempVal = QLineEdit("18℃")
        self.tempVal.setStyleSheet("font-size:50px")
        self.hboxTemp = QHBoxLayout()
        self.hboxTemp.addStretch(1)
        self.hboxTemp.addWidget(self.tempLabel)
        self.hboxTemp.addWidget(self.tempVal)
        self.hboxTemp.addStretch(1)
        self.humiLabel = QLabel(self)
        self.humiLabel.setText("湿度:")
        self.humiLabel.setStyleSheet("font-size:50px; color:white")
        self.humiVal = QLineEdit("55%")
        self.humiVal.setStyleSheet("font-size:50px")
        self.hboxHumi = QHBoxLayout()
        self.hboxHumi.addStretch(1)
        self.hboxHumi.addWidget(self.humiLabel)
        self.hboxHumi.addWidget(self.humiVal)
        self.hboxHumi.addStretch(1)
        self.vboxTempHumi = QVBoxLayout()
        self.vboxTempHumi.addLayout(self.hboxTemp)
        self.vboxTempHumi.addLayout(self.hboxHumi)

        #整体布局
        self.vboxMain = QVBoxLayout()
        self.vboxMain.addLayout(self.hBoxHeader)
        self.vboxMain.addStretch(1)
        self.vboxMain.addLayout(self.vboxTempHumi)
        self.vboxMain.addStretch(1)
        self.setLayout(self.vboxMain)
        
        #TCP服务线程获取DHT11温湿度数据
        self.tcpThread = TCPServer()
        self.tcpThread.signal_data.connect(self.updateShow) 
        self.tcpThread.start() 

        #信号与槽
        self.homeBtn.clicked.connect(self.returnHome)
        self.homeBtn.clicked.connect(self.close)
        
        self.initUI()

    # 初始化界面
    def initUI(self):
        self.resize(WIN_WIDTH, WIN_HEIGHT)
        self.setWindowTitle('温湿度')
        self.show()
        
    def paintEvent(self, event):
        palette = QPalette()
        pix = QPixmap("resource/bg/bg_dht11.png").scaled(self.width(),self.height())
        palette.setBrush(QPalette.Background,QBrush(pix))
        self.setPalette(palette)
      
    #更新温湿度
    def updateShow(self, temp, humi):
        self.tempVal.setText(temp + "℃")
        self.humiVal.setText(humi + "%")
        
    # 返回主页
    def returnHome(self):
        try:
            print("return home")
            self.tcpThread.stop()

            from homeUI import mainWindow
            self.homeWindow = mainWindow()
            self.homeWindow.show()
        except Exception as e:
            print(e)
            
if __name__ =='__main__':
    import sys
    app = QApplication(sys.argv)
    my_widget = DHT11Widget()
    my_widget.show()
    sys.exit(app.exec())
